package com.wendyxie.sproutup.service

import android.content.Context
import android.util.Log
import com.wendyxie.sproutup.db.SQLInitHelper
import com.wendyxie.sproutup.db.SQLUserDomainHelper
import com.wendyxie.sproutup.db.SQLUserScoreRecordHelper
import com.wendyxie.sproutup.db.SQLUserScoreTmplHelper
import com.wendyxie.sproutup.entity.UserScoreRecordEntity
import com.wendyxie.sproutup.utils.SPUtil
import java.time.LocalDateTime
import java.time.ZoneOffset

class Task {

    /**
     * 1、读取用户的定时积分任务
     * 2、检查当前时间和积分任务最后的执行时间，如果大于，则执行积分任务
     */
    fun checkUserScoreRecordTask(context: Context) {
        Log.d("checkUserScoreTmplTask", "checkUserScoreTmplTask start")
        val babyId = SPUtil.getBabyId(context)
        // 1. 读取用户的定时积分任务
        val userScoreTmplList = SQLUserScoreTmplHelper.queryListByBabyIdAndAuto(babyId, SQLInitHelper(context).openDatabase())
        // 2. 检查当前时间和积分任务最后的执行时间，如果大于，则执行积分任务
        for (userScoreTmplEntity in userScoreTmplList) {
            Log.d("checkUserScoreTmplTask", "userScoreTmplEntity.id: ${userScoreTmplEntity.id}")
            val userScore = SQLUserScoreRecordHelper.queryRecordListByTmplId(userScoreTmplEntity.id, SQLInitHelper(context).openDatabase())
            // 根据模板的频率和最后一次执行日期，判断需要追加几个积分任务
            var lastTime = 0L
            if (userScore == null) {
                lastTime = userScoreTmplEntity.createTime.toEpochSecond(ZoneOffset.UTC)
            } else {
                lastTime = userScore.scoreTime.toEpochSecond(ZoneOffset.UTC)
            }

            val nowTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)
            val diffTime = nowTime - lastTime
            val frequency = userScoreTmplEntity.frequency
            if (diffTime < 0) {
                Log.d("checkUserScoreTmplTask", "diffTime < 0")
                continue
            }
            var diffNum = when (frequency) {
                "DAY" -> {
                    // 天： 计算diffTime的差值是几天
                    diffTime / 86400
                }
                "WEEK" -> {
                    // 1周
                    diffTime / 604800
                }
                "MONTH" -> {
                    // 1月
                    diffTime / 2592000
                }
                else -> {
                    // 1年
                    0
                }
            }
            while (diffNum > 0) {
                // 执行积分任务
                val score = UserScoreRecordEntity(
                    userId = SPUtil.getUserId(context),
                    babyId = babyId,
                    score = userScoreTmplEntity.score,
                    scoreTitle = userScoreTmplEntity.scoreTitle,
                    scoreTmplId = userScoreTmplEntity.id
                )
                SQLUserDomainHelper.addUserScoreRecord(score, babyId, SQLInitHelper(context).openDatabase())
                diffNum -= 1
            }
        }
    }
}
